<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告提示区域 -->
      <el-alert
        title="警告: 只允许为第三级分类设置相关参数!"
        type="warning"
        :closable="false"
      ></el-alert>

      <!-- 商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类: </span>
          <el-cascader
            :options="cateList"
            clearable
            :props="cateProps"
            v-model="selectCateKeys"
            @change="handleChange"
          />
        </el-col>
      </el-row>

      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-change="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button size="small" type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加属性</el-button>
          <!-- 数据展示区域 -->
          <el-table :data="manyTableData" border row-key="attr_id">
            <el-table-column type="expand">
                 <template #default="scope">
                    <el-tag v-for="(item,i) of scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">{{ item }}</el-tag>
                     <el-input
                        v-if="scope.row.inputVisible"
                        ref="InputRef"
                        v-model="scope.row.inputValue"
                        class="ml-1 w-20"
                        size="small"
                        @keyup.enter="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)"
                    />
                    <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                 </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称">
                <template #default="scope">{{ scope.row.attr_name }}</template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="showEditDialog(scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="removeParams(scope.row)">删除</el-button>
                </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          <el-button size="small" type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加属性</el-button>
          <!-- 数据展示区域 -->
          <el-table :data="onlyTableData" border>
            <el-table-column type="expand">
                <template #default="scope">
                    <el-tag v-for="(item,i) of scope.row.attr_vals" :key="i" closable>{{ item }}</el-tag>
                    <el-input
                        v-if="inputVisible"
                        ref="InputRef"
                        v-model="inputValue"
                        class="ml-1 w-20"
                        size="small"
                        @keyup.enter="handleInputConfirm"
                        @blur="handleInputConfirm"
                    ></el-input>
                    <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput">+ New Tag</el-button>
                 </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称">
                <template #default="scope">{{ scope.row.attr_name }}</template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="showEditDialog(scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="removeParams(scope.row)">删除</el-button>
                </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加分类属性弹窗 -->
    <el-dialog :title="'添加' + titleText"  v-model="addDialogVisible" width="50%" @close="addDialogClosed">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
            <el-form-item :label="titleText" prop="attr_name">
                <el-input v-model="addForm.attr_name"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
        <span class="dialog-footer">
            <el-button @click="addDialogClosed()">取消</el-button>
            <el-button type="primary" @click="addParams" >确认</el-button>
        </span>
        </template>
    </el-dialog>


    <!-- 修改分类属性弹窗 -->
    <el-dialog :title="'修改' + titleText"  v-model="editDialogVisible" width="50%" @close="editDialogClosed">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
            <el-form-item :label="titleText" prop="attr_name">
                <el-input v-model="editForm.attr_name"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
        <span class="dialog-footer">
            <el-button @click="editDialogClosed()">取消</el-button>
            <el-button type="primary" @click="editParams" >确认</el-button>
        </span>
        </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from '../../http/axios.js'

export default {
  name: 'Params',
  data() {
    return {
      cateList: [], // 商品参数列表
      cateProps: {
        // 级联选择框的配置对象
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      selectCateKeys: [], // 级联选择框选中的数据
      activeName: 'many', //被激活的页签名称\
      manyTableData: [],
      onlyTableData: [],


      addDialogVisible: false , // 是否显示添加属性对话框
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
            {
                required: true,
                message: '参数名不能为空',
                trigger: 'blur'
            }
        ]
      },

      editDialogVisible: false,
      editForm: {
        attr_name: ''
      },
      editFormRules: {
        attr_name: [
            {
                required: true,
                message: '参数名不能为空',
                trigger: 'blur'
            }
        ]
      },

      inputVisible: false, // 控制输入和按钮的切换
      inputValue: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      // 获取所有的商品分类列表
      const { data: res } = await axios.get('categories')

      if (res.meta.status !== 200) {
        this.$message({
          type: 'error',
          message: '获取商品参数列表失败',
        })
      } else {
        this.cateList = res.data
      }
    },
    handleChange(newSelectCateKeys) {
      // 监听级联选择框的变化
      if (this.selectCateKeys == null || this.selectCateKeys.length !== 3) {
        this.manyTableData = [];
        this.onlyTableData = [];
        this.selectCateKeys = [];
        return;
      } else {
        this.handleTabClick();
      }
    },
    async handleTabClick() {    //   页签点击事件处理函数
      if (this.currendId !== null) {
        const { data: res } = await axios.get(`categories/${this.currendId}/attributes`,{params: { sel: this.activeName}});
        if (res.meta.status !== 200) {
          this.$message({
            type: 'error',
            message: '获取商品参数列表失败',
          })
        } else {
            res.data.forEach((item) => {
                item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : [];
                item.inputValue = '';
                item.inputVisible = false;
            });
           if(this.activeName == 'many'){
            this.manyTableData = res.data;
           }else if(this.activeName == 'only'){
            this.onlyTableData = res.data;
           }
        }
      }
    },
    addDialogClosed(){
        this.$refs.addFormRef.resetFields();
        this.addDialogVisible = false;
    },
    addParams(){ // 点击按钮，添加参数
        this.$refs.addFormRef.validate(async valid => {
            if(valid){
               const { data: res} = await axios.post(`categories/${this.currendId}/attributes`,{
                attr_name: this.addForm.attr_name,
                attr_sel: this.activeName
               });

               if(res.meta.status !== 201){
                this.$message({
                    type: 'error',
                    message: '添加' + this.titleText + '失败'
                })
               }else {
                this.$message({
                    type: 'success',
                    message: '添加' + this.titleText + '成功'
                });
                this.handleTabClick();
                this.addDialogClosed();
               }
            }
        })
    },

    editDialogClosed(){
        this.$refs.editFormRef.resetFields();
        this.editDialogVisible = false;
        this.editForm = { attr_name: '' };
    },
    editParams(){
        this.$refs.editFormRef.validate(async valid => {
            if(valid){
               const { data: res} = await axios.put(`categories/${this.currendId}/attributes/${this.editForm.attr_id}`,{
                attr_name: this.editForm.attr_name,
                attr_sel: this.activeName
               });

               if(res.meta.status !== 200){
                this.$message({
                    type: 'error',
                    message: '修改' + this.titleText + '失败'
                });
               }else{
                this.$message({
                    type: 'success',
                    message: '修改' + this.titleText + '成功'
                });
                 this.editDialogClosed();
                this.handleTabClick();
               }
            }
        })   
    },
    showEditDialog(dataInfo){
        this.editForm = JSON.parse(JSON.stringify(dataInfo));
        this.editDialogVisible = true
    },
    removeParams(dataInfo){
        this.$messageBox.confirm('此操作会永久删除该参数','提示',{
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(async ()=> {
            const { data: res} = await axios.delete(`categories/${this.currendId}/attributes/${dataInfo.attr_id}`);

            if(res.meta.status !== 200){
                this.$message({
                    type: 'error',
                    message: '删除失败'
                })
            }else{
                this.$message({
                    type: 'success',
                    message: '删除成功'
                });
                this.handleTabClick();
            }
        }).catch(() => {
        })
    },
    async handleInputConfirm(row){ // 文本失去焦点或者按下回车键
        if(row.inputValue.trim().length === 0){
            row.inputValue = '';
            row.inputVisible = false;
            return;
        }else{
            row.attr_vals.push(row.inputValue.trim());
            row.inputValue = '';
            row.inputVisible = false;
            this.saveAttriVals(row,'添加');
        } 
    },
    showInput(row){
        row.inputVisible = true;
        // 让文本自动获取焦点
        // nextTick 的方法的作用，就是在当页面上的元素重新渲染之后，才会指定回调函数中的代码
        this.$nextTick(() => {
            this.$refs.InputRef.$refs.input.focus();
        })
    },
    handleClose(i,row){
        row.attr_vals.splice(i,1);
        this.saveAttriVals(row,'删除');
    },
    async saveAttriVals(row,type){

        const { data: res} = await axios.put(`categories/${this.currendId}/attributes/${row.attr_id}`,{
            attr_name: row.attr_name,
            attr_sel: row.attr_sel,
            attr_vals: row.attr_vals.join(',')
        });

        if(res.meta.status !== 200){
            this.$message({
                type: 'error',
                message: type + '失败，服务区运行错误'
            });
        }else{
            this.$message({
                type: 'success',
                message: type + '成功'
            })
        }
    }
  },
  computed: {
    isBtnDisabled() {
      // 监听是否选择三级商品分类
      if (this.selectCateKeys == null || this.selectCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    currendId() {
      //返回当前选中的商品分类的id
      if (this.selectCateKeys == null || this.selectCateKeys.length !== 3) {
        return null
      } else {
        return this.selectCateKeys[2]
      }
    },
    titleText(){
        if(this.activeName == 'many'){
            return '动态属性';
        }else if(this.activeName == 'only'){
            return '静态属性';
        }
    }
  },
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}

.el-tag{
    margin: 5px;
}

.ml-1{
    width: 120px;
    margin: 5px;
}
</style>